//

//  YDBuyOptionsViewController.m
//  PeiZiWangBei
//
//  Created by 巨彦新 on 2018/3/2.
//  Copyright © 2018年 LK-IOS. All rights reserved.
//

#import "YDBuyOptionsViewController.h"
#import "YDInquiryResultController.h"//询价结果
#import "YDStockSearchViewController.h"//搜索界面
#import "YDVerticalStockBuyController.h"//股票详情


#import "YDBuySection0Cell.h"
#import "YDBuySection1Cell.h"
#import "YDBuySection2Cell.h"
#import "YDBuySection3Cell.h"

#import "YDBuyOptionM.h"
#import "YDAccountMonyModel.h"


@interface YDBuyOptionsViewController ()<UITableViewDelegate, UITableViewDataSource>


@property (nonatomic, strong)UITableView *tableView;

/**
 数据源
 */
@property (nonatomic, strong)NSMutableArray *buyOptionsList;


/**
 无数据
 */
@property (nonatomic , weak) SYNoDataView *dataView;

/**
 没网
 */
@property (nonatomic, strong)SYNoNetView *noNetView;


/**
 当前选中的申购model
 */
@property (nonatomic, strong)YDBuyOptionM *currentBuyM;

/**
 当前股票信息
 */
@property (nonatomic, strong)NSMutableDictionary *currentStock;


/**
 申请资金
 */
@property (nonatomic, strong)NSMutableArray *moneyList;

/**
 周期
 */
@property (nonatomic, strong)NSMutableArray *cycleList;


/**
 当前申请的资金
 */
@property (nonatomic, copy)NSString *currentWan;

@property (nonatomic, strong)YDBuySection1Cell *cell;

@property (nonatomic, strong)YDBuySection0Cell *cell0;

//顶部安全区域
@property (nonatomic , assign) CGFloat safeTopH;
//底部安全区域
@property (nonatomic , assign) CGFloat safeBottomH;

//是不是正在刷新
@property (nonatomic , assign) BOOL stockIsRunning;

//定时器
@property (nonatomic , strong) NSTimer *oneStockTimer;

//有问题的股票
@property (nonatomic, assign)BOOL isUnnormalStock;

@end

@implementation YDBuyOptionsViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"申购";
    
    self.safeTopH = isPhoneX ? 84 : 64;
    self.safeBottomH = self.isHiddenTabbar ? 0 : (isPhoneX ? 83 : 49);
    [self getStockNewMarket];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hideKeyBoard) name:@"hideKeyBoard" object:nil];
    [self setUpDataManger];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self viewStopTimer];
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self viewOpenTimer];
}

-(void)viewOpenTimer
{
    if (self.oneStockTimer)return;
    if (![NSDate stockTradingTimeJudgment])return;
    DDLog(@"开启定时器")
    self.oneStockTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(timeLoadStock) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.oneStockTimer forMode:NSRunLoopCommonModes];
    
}
-(void)viewStopTimer
{
    if (!self.oneStockTimer)return;
    DDLog(@"关闭定时器")
    [self.oneStockTimer invalidate];
    self.oneStockTimer = nil;
}

-(NSMutableArray *)buyOptionsList
{
    if (!_buyOptionsList) {
        _buyOptionsList = [NSMutableArray array];
    }
    return _buyOptionsList;
}
-(NSMutableArray *)moneyList
{
    if (!_moneyList) {
        _moneyList = [NSMutableArray new];
    }
    return _moneyList;
}
-(NSMutableDictionary *)currentStock
{
    if (!_currentStock) {
        _currentStock = [NSMutableDictionary new];
    }
    return _currentStock;
}
-(NSMutableArray *)cycleList
{
    if (!_cycleList) {
        _cycleList = [NSMutableArray array];
    }
    return _cycleList;
}

- (void)removeNodataView
{
    if (_dataView != nil) {
        [_dataView removeFromSuperview];
        _dataView = nil;
    }
}
- (void)removeNoNetView
{
    if (_noNetView != nil) {
        [_noNetView removeFromSuperview];
        _noNetView = nil;
    }
}
-(void)setUpDataManger
{
    MJGIFHeader *header = [MJGIFHeader headerWithRefreshingTarget:self refreshingAction:@selector(getStockNewMarket)];
    //隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES ;
    //隐藏状态
    header.stateLabel.hidden = YES ;
    self.tableView.mj_header = header;
    
    
}

//加载单只股票信息
-(void)getStockNewMarket
{
    self.stockIsRunning = YES;
    self.stockCode = self.stockCode ? : @"000001";
    NSString *url = [NSString stringWithFormat:@"%@%@",@"/stock/market/" , self.stockCode];
    NSString *baseUrl = [NSString stringWithFormat:@"%@%@",baseUrlHttp , url];
    NSString *authToken = [[SYUserDataManger sharedInstance] getUserToken];
    BaseNetRequest *request = [[BaseNetRequest alloc] initWithRequestMethod:GETMethod];
    [request sessionRequestWithDictionary:nil andURLString:baseUrl andAuthToken:authToken WithSuccessBlock:^(NSDictionary *resultDict) {
       
          self.stockIsRunning = NO;
        [self.tableView.mj_header endRefreshing];
        DDLog(@"resultDict = %@" , resultDict)
        if ([resultDict[@"code"] integerValue] == 200) {
            self.currentStock = resultDict[@"result"];
            [self removeNoNetView];
            [self loadData];
            if ([resultDict[@"result"][@"status"] integerValue] == 1) {
             self.isUnnormalStock = NO;
            }else{
       
                self.isUnnormalStock = YES;
                
            }
            
        }else{
            
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                            WithType:NavTipsViewTypeMessage text:resultDict[@"message"]
                                                          isExistNav:YES];
            if (!self.currentStock.count) {
                
                [self noNetView];
            }
        }
    } failBlock:^(NSError *error) {
        self.stockIsRunning = NO;
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                        WithType:NavTipsViewTypeMessage text:@"网络异常"
                                                      isExistNav:YES];
        if (!self.currentStock.count) {
            
             [self noNetView];
        }
       
    }];
}
- (void)loadData
{

    
    [BaseNetRequest sessionRequestWithparameters:nil method:GETMethod requstType:OptionsCycle WithSuccessBlock:^(NSDictionary *resultDict) {
  

        DDLog(@"resultDict = %@" , resultDict)
        
        if ([resultDict[@"code"] integerValue] == 200) {
            [self.buyOptionsList removeAllObjects];
            self.buyOptionsList = [YDBuyOptionM mj_objectArrayWithKeyValuesArray:resultDict[@"result"]];
          
            //配置cell的数据源
            [self configurationDataSource];
            [self.tableView reloadData];
     
        }
        else
        {
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:resultDict[@"message"] isExistNav:YES];
        }
    } failBlock:^(NSError *error) {
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"信息加载出错，请重试~" isExistNav:YES];
    }];
}


- (void)configurationDataSource
{
    

    self.currentBuyM = [self.buyOptionsList firstObject];
    [self.moneyList removeAllObjects];
    [self.cycleList removeAllObjects];
    
    for (int i = 0; i < self.currentBuyM.amountValues.count; i++) {
        YDAccountMonyModel *model = [self.currentBuyM.amountValues objectAtIndex:i];
        [self.moneyList addObject:model.wanMount];
        
        if (i == 0) {
            self.currentWan = model.wanMount;
        }
    }
    
    for (int i = 0; i < self.buyOptionsList.count; i++) {
        YDBuyOptionM *model = [self.buyOptionsList objectAtIndex:i];
        [self.cycleList addObject:model.name];
    }
    
}



/**
 询价
 */
- (void)xunjia
{
  // GET /stockoptiontrade/{stockCode}/{cycle}/quote
    
    if (![SYUserInformation sharedInstance].isLogin) {
        //没有登录直接弹登录页面
        [self presentLoginVC];
        return;
    }
    if (self.isUnnormalStock) {
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"改股票现已停牌，请留意实时信息" isExistNav:YES];
        return;

    }
    
    YDBuyOptionM *m =   [self.buyOptionsList firstObject];
    
    NSNumber *maxMoeny = m.limitNominalAmount;
    
    if (maxMoeny.integerValue <= 0) {
        maxMoeny = @10000000000;
    }
    
    NSString *wan = self.cell.moneyTextField.text.length ? self.cell.moneyTextField.text : self.currentWan;
    if (wan.integerValue % 5 != 0 || wan.integerValue <5 || wan.integerValue > maxMoeny.integerValue/10000) {
        //提示
        NSString *tips;
        if (m.limitNominalAmount.integerValue <= 0 ) {
            //无限制
            tips = @"名义本金最低5万且为5万的整数倍";
        }
        else
        {
            tips = [NSString stringWithFormat:@"名义本金最低5万且为5万的整数倍,最高%ld万",maxMoeny.integerValue/10000];
        }
        
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                   WithType:NavTipsViewTypeMessage
                                                       text:tips
                                                 isExistNav:YES];
        return;
    }
    
    
     [[SYProgressHUD sharedInstance] showMBHudWithSting:@"加载中..."];
    NSString *money = self.cell.moneyTextField.text.length ?self.cell.moneyTextField.text : self.currentWan;
    
    NSString *url = [NSString stringWithFormat:@"/stockoptiontrade/%@/%@/quote?nominalAmount=%@" , self.stockCode,self.currentBuyM.cycle,@(money.floatValue *10000)];
    
    NSString *baseUrl = [NSString stringWithFormat:@"%@%@",baseUrlHttp , url];
    NSString *authToken = [[SYUserDataManger sharedInstance] getUserToken];
    BaseNetRequest *request = [[BaseNetRequest alloc] initWithRequestMethod:GETMethod];
    [request sessionRequestWithDictionary:nil andURLString:baseUrl andAuthToken:authToken WithSuccessBlock:^(NSDictionary *resultDict) {
        
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        //            DDLog(@"resultDict = %@" , resultDict)
        if ([resultDict[@"code"] integerValue] == 200) {
            
            NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:resultDict[@"result"]];
            
            [dic setObject:self.cell.moneyTextField.text.length ?self.cell.moneyTextField.text : self.currentWan forKey:@"money"];
            [dic setObject:self.currentBuyM.name forKey:@"optionsTime"];
            [dic setObject:[self.currentStock objectForKey:@"name"] forKey:@"stockName"];
            
            [dic setObject:[self.currentStock objectForKey:@"instrumentId"] forKey:@"stockCode"];
            [dic setObject:@(self.currentBuyM.ID) forKey:@"cycleId"];
            
            YDInquiryResultController *vc = [[YDInquiryResultController alloc] init];
            vc.buyDic = dic;
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
            
        }else{
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                       WithType:NavTipsViewTypeMessage text:resultDict[@"message"]
                                                     isExistNav:YES];
        }
        
    } failBlock:^(NSError *error) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                        WithType:NavTipsViewTypeMessage text:@"询价失败"
                                                      isExistNav:YES];
    }];
    
    
    
}
/**
 刷新section
 */
- (void)refreshSectionWithIndex:(NSInteger)index
{
    NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:index];
    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LK(weakSelf);
    switch (indexPath.section) {
        case 0:
        { YDBuySection0Cell *cell = [[YDBuySection0Cell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"YDBuySection0Cell"];
            cell.stockDic = self.currentStock;
            self.cell0 = cell;
            [cell setClickBack:^(NSString *title) {
                if ([title isEqualToString:@"搜索"]) {
                    YDStockSearchViewController *vc = [[YDStockSearchViewController alloc] init];
                    vc.searchStyle = Search_Present;
                    
                    
                    [vc setDissBack:^(NSString *stockName, NSString *stockCode) {

                        weakSelf.stockCode = stockCode;

                        [weakSelf getStockNewMarket];
                    }];
                    YDBaseNavigationController *baseNav = [[YDBaseNavigationController alloc] initWithRootViewController:vc];
                    [self presentViewController:baseNav animated:YES completion:nil];
                    
                }else if ([title isEqualToString:@"详情"])
                {
                    //点击搜索进入股票详情
                    
                    YDVerticalStockBuyController *vc = [[YDVerticalStockBuyController alloc] init];
                    vc.isNormal = YES;
                    vc.isActivity = NO;
                    vc.isPopToRootC = YES;
                    vc.optionStyle = SYVerticalStockButtonOptionViewStyle3;
                    vc.stockCode = weakSelf.stockCode;
                    vc.hidesBottomBarWhenPushed = YES;
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                }
                else if ([title isEqualToString:@"问号"])
                {
                    [weakSelf showAlertWithTitle:@"标的股票" Message:@"禁止买入st、*st、上市日期不足6个月、涨跌停板状态、或者其他被限制的股票"];
                }
                
                
            }];
            
            return cell;
        }
            break;
        case 1:
        { YDBuySection1Cell *section1cell = [[YDBuySection1Cell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"YDBuySection1Cell"];
            section1cell.moneylist = self.moneyList;
            self.cell = section1cell;
            [section1cell setClickBack:^(NSInteger index) {
                NSString *wan = [weakSelf.moneyList objectAtIndex:index];
                weakSelf.currentWan = wan;
            }];
            return section1cell;
        }
            break;
        case 2:
        { YDBuySection2Cell *cell = [[YDBuySection2Cell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"YDBuySection2Cell"];
            cell.cycleList = self.cycleList;
            [cell setClickBack:^(NSString *title, NSInteger index) {
                if ([title isEqualToString:@"问号"])
                {
                    [weakSelf showAlertWithTitle:@"策略周期" Message:@"1、即用户行使权利的策略周期，用户可在策略周期任意时间内卖出，或者自动到期卖出。所选的策略周期越长，所需要的策略风控服务费就越高。\n2、两周的周期计算，实际可交易天数为11天。\n3、到期日如果为非交易日则提前至到期前最后一个交易日"];
                }
                else
                {
                    weakSelf.currentBuyM = [self.buyOptionsList objectAtIndex:index];
                
                }
            }];
            

           
            
            return cell;
        }
            break;
        case 3:
        { YDBuySection3Cell *cell = [[YDBuySection3Cell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"YDBuySection3Cell"];
            [cell setClickBack:^(NSString *title) {
                if ([title isEqualToString:@"确定买入"]) {
                    [weakSelf xunjia];
                }
                else if ([title isEqualToString:@"问号"])
                {
                    [weakSelf showAlertWithTitle:@"买入方式" Message:@"甲方即时进行申报买入，期初买入价格以甲方实际买入价格为准。（申报后5分钟内实际成交均价）买入交易时段为，交易日10:30分至14:55时间区间中的交易时段。平台不保证任何成交价格和成交时间，一切均以实际成交数据为准。"];
                }
                
            }];
            
            return cell;
        }
            break;
            
        default:
            return [UITableViewCell new];
            break;
    }
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor colorWithHexString:mainGray];
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return isPhoneX ? rateX812(5) :rate750(5);
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 3:
            return  isPhoneX ? rateX812(139) :rate750(139);
            break;
        case 1:
            return isPhoneX ? rateX812(150) :rate750(150);
        default:
            return  isPhoneX ? rateX812(100) :rate750(100);
            break;
    }
    
}
/*******tableView********/
-(UITableView *)tableView
{
    if (_tableView == nil) {

        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, LKScreenW, LKScreenH - self.safeTopH - self.safeBottomH) style:UITableViewStylePlain];
        
        [self.view addSubview:tableView];
        tableView.backgroundColor = [UIColor whiteColor];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        // tableView.contentInset = UIEdgeInsetsMake(0, rate375(7),0, rate375(7));
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.showsVerticalScrollIndicator = NO;
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        tableView.tableFooterView = [UIView new];
        tableView.userInteractionEnabled = YES;
        [tableView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyBoard)]];
        if (isIos11) {
            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView = tableView;
    }
    return _tableView;
}
- (void)hideKeyBoard
{
    [self.cell.contentView endEditing:YES];
}
/*******dataView********/
-(SYNoDataView *)dataView
{
    if (_dataView == nil) {
        CGFloat dataW = rate375(240);
        CGFloat dataX = (LKScreenW - dataW) * 0.5;
        CGFloat dataH = isPhoneX ? rateX812(196) : rate750(196);
        CGFloat dataY = isPhoneX ? rateX812(132) : rate750(132);
        CGRect frame = CGRectMake(dataX, dataY, dataW, dataH);
        //wuneirong   wuxinhao
        SYNoDataView *dataView = [SYNoDataView positionNoDataViewInitWithFrame:frame ImageString:@"wuneirong" buttonTitle:@"" IsCanSeeBuyButton:NO];
        [self.tableView addSubview:dataView];
        _dataView = dataView;
    }
    return _dataView;
}

-(SYNoNetView *)noNetView
{
    if (_noNetView == nil) {
        SYNoNetView *noNetView = [[SYNoNetView alloc] init];
        [self.tableView addSubview:noNetView];
        
        [noNetView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.bottom.equalTo(self.view);
//            make.top.equalTo(isPhoneX ? @(rateX812(40)) : @(rate750(40)));
        }];
        LK(weself)
        [noNetView setClickBlock:^(BOOL isClick) {
            [weself.tableView.mj_header beginRefreshing];
            
        }];
        _noNetView = noNetView;
    }
    return _noNetView;
}
- (void)showAlertWithTitle:(NSString *)title Message: (NSString *)message
{

    PZTipsAlertView *alert = [PZTipsViewManger shareSingleTipsAlertViewTitle:title Mesage:message ButtonTitle:@"我知道了" ButtonClickBlock:^{
        [self.pz_popupController dismiss];
   
        
        
    }];
    self.pz_popupController = [[PZPopUpController alloc] init];
    [self.pz_popupController dropAnimatedWithRotateAngle:30];
    [self.pz_popupController presentContentView:alert duration:0.75 springAnimated:YES];
}

- (void)presentLoginVC
{
    YDLoginController *loginVC = [[YDLoginController alloc] init];
    loginVC.loginStyle = Login_Present;
    YDBaseNavigationController *baseNav = [[YDBaseNavigationController alloc] initWithRootViewController:loginVC];
    [self presentViewController:baseNav animated:YES completion:nil];
}


- (void)timeLoadStock
{
    if (self.stockIsRunning)return;
    self.stockIsRunning = YES;
    
    self.stockCode = self.stockCode ? : @"000001";
    NSString *url = [NSString stringWithFormat:@"%@%@",@"/stock/market/" , self.stockCode];
    NSString *baseUrl = [NSString stringWithFormat:@"%@%@",baseUrlHttp , url];
    NSString *authToken = [[SYUserDataManger sharedInstance] getUserToken];
    BaseNetRequest *request = [[BaseNetRequest alloc] initWithRequestMethod:GETMethod];
    [request sessionRequestWithDictionary:nil andURLString:baseUrl andAuthToken:authToken WithSuccessBlock:^(NSDictionary *resultDict) {
        
        self.stockIsRunning = NO;
        if ([resultDict[@"code"] integerValue] == 200 && resultDict[@"result"][@"lastPrice"]) {
            self.cell0.stockDic = resultDict[@"result"];
        }
    } failBlock:^(NSError *error) {
        self.stockIsRunning = NO;
    }];
}
@end
